<?php
namespace Home\Controller;
use Think\Controller;
class IndexController extends Controller {
	public function login(){
		if(IS_POST){
			$obj=(object)[];
			$obj->data=$_POST;
			$m=M("user");
			$ret=$m->where("uname='{$obj->data['uname']}' and password='{$obj->data['password']}'")->select();
			if($ret){
				//开启回话
				session_start();
				$_SESSION["uname"]=$ret[0]["uname"];
				$_SESSION["uid"]=$ret[0]["uid"];
				//查询用户权限
				$ag=M("auth_group");
				$result1=$ag->field("rules")->join('think_auth_group_access ON think_auth_group.id=think_auth_group_access.group_id')->where("uid='{$ret[0]["uid"]}'")->find();
				$ar=M("auth_rule");
				$result2=$ar->where("id in(".$result1["rules"].") and is_menu = 0")->select();
				if($result2){
					$str1="";
					//拼接字符串,方法的id
					for ($i=0; $i <count($result2) ; $i++) {
						if($i<count($result2)-1){
							$str1.=$result2[$i]["pid"].",";
						}else{
							$str1.=$result2[$i]["pid"];
						}
					}
				    $id=$ar->where("id in(".$str1.") and is_menu = 1")->select();
					$str="";
					//拼接字符串,方法的id
					for ($i=0; $i <count($id) ; $i++) {
						if($i<count($id)-1){
							$str.=$id[$i]["id"].",";
						}else{
							$str.=$id[$i]["id"];
						}
					}
					//如果有方法功能	
					$userrule=$ar->where("id in(".$result1["rules"].") or id in(".$str.") and is_menu =1")->select();	
				}else{
					$userrule=$ar->where("id in(".$result1["rules"].") and is_menu =1")->select();	
				}
				$obj->code=0;
			    $obj->message="登录成功";
			    $obj->userrule=$userrule;
				$this->ajaxReturn($obj);	
			}else{
				$obj->code=1;
			    $obj->message="用户名或密码不正确";
			    $this->ajaxReturn($obj);
			}
		}else if(IS_GET){
			$this->display("login");
		}
	}
	

}
